//
//  SWEventsViewController.swift
//  ChildStory
//
//  Created by linhan on 2016/11/11.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWEventsViewController: SWBaseViewController,UITableViewDataSource,UITableViewDelegate,SWAPIComponent,ScrollTabBarDelegate,SWGlobalPopupMenu
{
    var popupMenuController:AnyObject?
    
    private var _list:[SWKidEvent] = []
    private var _summary:SWStageSummary?
    private var _total:Int = 0
    
    private var _hasSummary:Bool{
        return _summary != nil
    }
    
    private var _hasEvents:Bool{
        return _list.count > 0
    }
    
    //是否展开
    private var _extended:Bool = false{
        didSet{
            if _extended != oldValue
            {
                let count:Int = _summary?.events?.count ?? 0
                if count > 0
                {
                    let paths:[IndexPath] = (1...count).map({IndexPath(row: $0, section: 1)})
                    if _extended
                    {
                        _tableView.insertRows(at: paths, with: .fade)
                        _tableView.scrollToRow(at: IndexPath(row: 0, section: 1), at: .top, animated: true)
                    }
                    else
                    {
                        _tableView.deleteRows(at: paths, with: .fade)
                    }
                }
                
                _tableFooterView?.extended = _extended
                
            }//!= oldValue
        }//end didSet
    }
    
    private var _tabBar:ScrollTabBar?
    lazy private var _statusLabel:UILabel = UILabel()
    lazy private var _tableView:UITableView = UITableView()
    lazy private var _takePhotoBtn:UIButton = UIButton(type:.custom)
    lazy private var _albumBtn:UIButton = UIButton(type:.custom)
    private var _tableFooterView:SWTableFooterView?
    lazy private var _refreshStatusView = EventsPullRefreshStatusView(frame: CGRect(x: 0,y: 0,width: 100,height: 110))
    
    deinit
    {
        NotificationCenter.default.removeObserver(self)
        trace("DEINIT SWEventsViewController")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    private func setup()
    {
        title = "咿呀"
        automaticallyAdjustsScrollViewInsets = false
        view.backgroundColor = UIColor.white
        
        var lastBottom:CGFloat = 0
        lastBottom = createTabBar(y: navigationBarBottom, container: view)
        lastBottom = createStatusView(y: lastBottom, container: view)
        createTableView(y: lastBottom, container: view)
        createTableFooterView()
        
        globalPopupMenuSetup(container: view)
        
        SWNotificationCenter.addObserver(self, selector: #selector(assetClassifiedNotification(_:)), name: NotificationName.AssetClassified, object: nil)
        
        SWNotificationCenter.addObserver(self, selector: #selector(childAccountInfoChangedNotification), name: NotificationName.ChildAccountInfoChanged, object: nil)
        
        loadData()
        statusViewUpdate()
    }
    
    //
    private func createTabBar(y:CGFloat, container:UIView) -> CGFloat
    {
        let tabBar:ScrollTabBar = ScrollTabBar(frame: CGRectMake(0, y, view.width, 40))
        tabBar.font = UIFont.systemFont(ofSize: 14)
        tabBar.itemSpacing = 30
        tabBar.itemTitleLeftMargin = 10
        tabBar.alignment = .left
        tabBar.selectedColor = UIColor(hex: 0x2f3231)
        tabBar.unselectedColor = UIColor(hex: 0xababab)
        tabBar.delegate = self
        container.addSubview(tabBar)
        _tabBar = tabBar
        return tabBar.bottom
    }
    
    //状态栏
    private func createStatusView(y:CGFloat, container:UIView) -> CGFloat
    {
        let statusView = UIView()
        statusView.frame = CGRectMake(0, y, view.width, 40)
        statusView.backgroundColor = UIColor(hex:0xf6f0f2)
        container.addSubview(statusView)
        
        let topLine:UIView = UIView()
        topLine.backgroundColor = UIColor(hex: 0xd3d3d3)
        topLine.frame = CGRectMake(0, 0, statusView.width, 1)
        statusView.addSubview(topLine)
        
        let favoriteBtn:UIButton = UIButton(type: .system)
        favoriteBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        favoriteBtn.setTitle("我的收藏", for: .normal)
        favoriteBtn.setTitleColor(UIColor(hex:0x474747), for: .normal)
        favoriteBtn.sizeToFit()
        favoriteBtn.center = CGPointMake(statusView.width - favoriteBtn.width * 0.5 - 15, statusView.height * 0.5)
        favoriteBtn.addTarget(self, action: #selector(favoriteBtnTapped), for: .touchUpInside)
        statusView.addSubview(favoriteBtn)
        
        let icon:UIImageView = UIImageView(image:UIImage(named:"event_icon_favorite"))
        icon.center = CGPointMake(favoriteBtn.x - icon.width * 0.5 - 10, statusView.height * 0.5)
        statusView.addSubview(icon)
        
        let statusLabelX:CGFloat = 15
        _statusLabel.textColor = UIColor(hex: 0x737272)
        _statusLabel.font = UIFont.systemFont(ofSize: 14)
        _statusLabel.frame = CGRectMake(statusLabelX, 0, icon.x - statusLabelX, statusView.height)
        statusView.addSubview(_statusLabel)
        
        let bottomLine:UIView = UIView()
        bottomLine.backgroundColor = UIColor(hex: 0xd3d3d3)
        bottomLine.frame = CGRectMake(0, statusView.height - 1, statusView.width, 1)
        statusView.addSubview(bottomLine)
        
        return statusView.bottom
    }
    
    private func createTableView(y:CGFloat, container:UIView)
    {
        _tableView.frame = CGRectMake(0, y, view.width, view.height - y)
        _tableView.contentInset = UIEdgeInsetsMake(15, 0, 0, 0)
        _tableView.backgroundColor = UIColor(hex:0xefefef)
        _tableView.separatorStyle = .none
        _tableView.tableFooterView = UIView()
        _tableView.dataSource = self
        _tableView.delegate = self
        container.addSubview(_tableView)
        setupRefresh()
    }
    
    private func createTableFooterView()
    {
        let tapGesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(footerViewTapped))
        let tableFooterView = SWTableFooterView(frame: CGRectMake(0, 0, view.width, 28))
        tableFooterView.addGestureRecognizer(tapGesture)
        _tableFooterView = tableFooterView
    }
    
    private func setupRefresh()
    {
        _tableView.addPullToRefreshWithAction({
            self._tableView.willStopPullToRefresh(0.5)
        }, withAnimator: _refreshStatusView)
    }
    
    //阶段栏更新
    private func stageBarUpdate()
    {
        let lockIcon:UIImage? = UIImage(named: "event_icon_lock")
        let days:Int = SWAccountManager.sharedManager().account?.child?.days ?? 0
        let stages:[SWStage] = SWConfigManager.sharedManager().stages
        let currentStageID:String = SWConfigManager.sharedManager().currentStageID
        let titles:[String] = stages.map({$0.title})
        let items:[SWScrollTabBarItem] = stages.map({SWScrollTabBarItem(title: $0.title, image:$0.start > days ? lockIcon : nil)})
        let index:Int = stages.index(where: {($0.stageID ?? "") == currentStageID}) ?? 0
        _tabBar?.items = items
        _tabBar?.selectedIndex = index
        
        
        if let stageID = stages.valueAt(index)?.stageID
        {
            loadEvents(stageID: stageID)
            loadStageSummary(stageID: stageID)
        }
    }
    
    private func statusViewUpdate()
    {
        let days:String = SWAccountManager.sharedManager().account?.child?.daysString ?? ""
        _statusLabel.text = "宝宝\(days)了"
    }
    
    private func loadData()
    {
        if SWConfigManager.sharedManager().stages.count > 0
        {
            stageBarUpdate()
        }
        else
        {
            let req = SWStagesFetchReq()
            req.successCallback = {[weak self] response,cache in
                if let response = response as? SWStagesFetchRsp,
                    let stages = response.stages?.flatMap({SWStage(response: $0)})
                {
                    SWConfigManager.sharedManager().stages = stages
                    SWConfigManager.sharedManager().currentStageID = "\(response.currentStageID ?? 0)"
                    self?.stageBarUpdate()
                }
            }
            load(req)
        }
    }
    
    private func loadEvents(stageID:String)
    {
        let req = SWEventsFetchReq()
        req.stageID = stageID
        req.successCallback = {[weak self] response,cache in
            if let response = response as? SWEventsFetchRsp
            {
                self?._list.removeAll()
                
                if let events:[SWKidEvent] = response.events?.flatMap({SWKidEvent(response: $0)})
                {
                    self?._total = response.count ?? 0
                    self?._list = events
                }
                
                self?.tableViewReloadData()
            }
        }
        load(req)
    }
    
    private func loadStageSummary(stageID:String)
    {
        let req = SWStageSummaryReq()
        req.stageID = stageID
        req.successCallback = {[weak self] response,cache in
            if let response = response as? SWStageSummaryRsp
            {
                self?._summary = nil
                self?._summary = SWStageSummary(response: response)
                self?.tableViewReloadData()
            }
        }
        load(req)
    }
    
    private var _tableViewReloadID:String = ""
    private func tableViewReloadData()
    {
        clearTimeout(_tableViewReloadID)
        _tableViewReloadID = setTimeout(0.2, closure: {[weak self] in
            self?.tableViewReloadDelay()
        })
    }
    
    private func tableViewReloadDelay()
    {
        _refreshStatusView.days = 6
        _refreshStatusView.events = "《宝宝对声音的回应》"
        _tableView.tableFooterView = _hasSummary && _hasEvents ? _tableFooterView : UIView()
        _tableView.reloadData()
    }
    
    func numberOfSections(in tableView: UITableView) -> Int
    {
        //如果解锁了，事件列表在Section0，概要在Section1
        return _hasSummary && _hasEvents ? 2 : 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        var count:Int = 0
        let summaryCount:Int = (_summary?.events?.count ?? 0)
        if section == 0
        {
            count = _hasEvents ? _list.count : (_hasSummary ? summaryCount + 1 : 0)
        }
        else
        {
            count = _extended ? summaryCount + 1 : 1
        }
        return count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
    {
        let cellWidth:CGFloat = view.width
        let fetchStageSummaryCellHeight:(Int)->CGFloat = {[weak self] index in
            if let summary = self?._summary?.events?.valueAt(index - 1) as? SWKidEventSummary
            {
                return SWStageSummaryCell.getCellHeight(summary:summary, cellWidth: cellWidth)
            }
            return 0
        }
        
        let fetchStageSummaryHeader:(Void)->CGFloat = {[weak self] in
            if let summary = self?._summary
            {
                return SWStageSummaryHeader.getCellHeight(summary: summary, cellWidth: cellWidth)
            }
            return 0
        }
        
        var height:CGFloat = 0
        if indexPath.section == 0 && _hasEvents
        {
            let CellGrid:CGFloat = 8
            height = SWKidEventCell.getCellHeight(cellWidth: view.width) + CellGrid
        }
        else
        {
           height = indexPath.row == 0  ? fetchStageSummaryHeader() : fetchStageSummaryCellHeight(indexPath.row)
        }
        return height
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        var cell:UITableViewCell?
        if indexPath.section == 0 && _hasEvents
        {
            let identifier:String = "SWKidEventCell"
            cell = tableView.dequeueReusableCell(withIdentifier: identifier)
            if cell == nil
            {
                cell = SWKidEventCell(style: .default, reuseIdentifier: identifier, cellWidth: view.width)
                //(cell as? SWFeedFlowCell)?.delegate = self
            }
            (cell as? SWKidEventCell)?.event = _list.valueAt(indexPath.row)
        }
        else
        {
            if indexPath.row == 0
            {
                let identifier:String = "SWStageSummaryHeader"
                cell = tableView.dequeueReusableCell(withIdentifier: identifier)
                if cell == nil
                {
                    cell = SWStageSummaryHeader(style: .default, reuseIdentifier: identifier, cellWidth: view.width)
                }
                (cell as? SWStageSummaryHeader)?.summary = _summary
            }
            else
            {
                let identifier:String = "SWStageSummaryCell"
                cell = tableView.dequeueReusableCell(withIdentifier: identifier)
                if cell == nil
                {
                    cell = SWStageSummaryCell(style: .default, reuseIdentifier: identifier, cellWidth: view.width)
                }
                (cell as? SWStageSummaryCell)?.summary = _summary?.events?.valueAt(indexPath.row - 1) as? SWKidEventSummary
            }
        }
        return cell ?? UITableViewCell(style: .default, reuseIdentifier: "")
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        tableView.deselectRow(at: indexPath, animated: false)
        if indexPath.section == 0 && _hasEvents
        {
            if let event = _list.valueAt(indexPath.row)
            {
                let viewController = SWEventDetailViewController()
                viewController.eventID = event.eventID ?? ""
                navigationController?.pushViewController(viewController, animated: true)
            }
        }
    }
    
    
    //MARK ================================= ScrollTabBarDelegate =========================
    func scrollTabBar(_ tabBar: ScrollTabBar, didSelectIndex index: Int)
    {
        let stages:[SWStage] = SWConfigManager.sharedManager().stages
        if let stageID = stages.valueAt(index)?.stageID
        {
            loadEvents(stageID: stageID)
            loadStageSummary(stageID: stageID)
        }
    }
    
    @objc private func assetClassifiedNotification(_ notification:Notification)
    {
        if let eventID = notification.userInfo?[SWKey.eventID] as? String,
           let index = _list.index(where: {($0.eventID ?? "") == eventID})
        {
            _tableView.reloadRows(at: [IndexPath(row:index,section:0)], with: .none)
        }
    }
    
    @objc private func takePhotoBtnTapped()
    {
        let viewController = SWTakePhotoViewController()
        viewController.delegate = self
        let navigation = SWBaseNavigationController(rootViewController: viewController)
        present(navigation, animated: true, completion:nil)
    }
    
    @objc private func albumBtnTapped()
    {
        navigationController?.pushViewController(SWAlbumViewController(), animated: true)
    }
    
    @objc private func favoriteBtnTapped()
    {
        //TODO
        //navigationController?.pushViewController(SWEventFavoriteViewController(), animated: true)
        
        let viewController = SWEventDetailViewController()
        viewController.eventID = "3"
        navigationController?.pushViewController(viewController, animated: true)
    }
    
    @objc private func footerViewTapped()
    {
        _extended = !_extended
    }
    
    @objc private func childAccountInfoChangedNotification()
    {
        statusViewUpdate()
    }
    
    
}

fileprivate class SWTableFooterView: UIView
{
    
    var extended:Bool = false {
        didSet{
            _label.text = extended ? "收起" : "阶段详情"
            _arrow.transform = extended ? CGAffineTransform.identity : CGAffineTransform(scaleX: 1, y: -1)
        }
    }
    
    private var _label:UILabel = UILabel()
    private var _arrow:UIImageView = UIImageView(image:UIImage(named:"event_icon_arrow_extend"))
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setup()
    {
        let backgroundView = UIView()
        backgroundView.frame = CGRectMake(15, 0, width - 30, height)
        backgroundView.backgroundColor = UIColor.white
        addSubview(backgroundView)
        
        let labelWidth:CGFloat = 60
        _label.textAlignment = .right
        _label.font = UIFont.systemFont(ofSize: 11)
        _label.textColor = UIColor(hex: 0x595858)
        _label.frame = CGRectMake((width - labelWidth) * 0.5, 0, labelWidth, height)
        addSubview(_label)
        
        _arrow.center = CGPointMake(_label.right + _arrow.width, height * 0.5)
        addSubview(_arrow)
        
        extended = false
    }
    
    
}
